<template>
  <div class="login-container">
    <el-form v-show="!isForget" ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"
             auto-complete="on" label-position="left">
      <div class="title-container">
        <h3 class="title">Fastdev Admin</h3>
      </div>
      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user"/>
        </span>
        <el-input ref="username" v-model="loginForm.username" placeholder="Username" name="username" type="text"
                  tabindex="1" auto-complete="on"/>
      </el-form-item>
      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password"/>
        </span>
        <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
                  placeholder="Password" name="password" tabindex="2" auto-complete="on"
                  @keyup.enter.native="handleLogin"/>
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"/>
        </span>
      </el-form-item>
      <el-button class="forget" type="text" @click="forgetPwd">忘记密码？</el-button>
      <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;"
                 @click.native.prevent="handleLogin">Login
      </el-button>
    </el-form>
    <el-form v-show="isForget" ref="forgetForm" :model="forgetForm" :rules="forgetRules" class="login-form"
             label-position="left">
      <div class="title-container">
        <h3 class="title">忘记密码</h3>
      </div>
      <el-form-item prop="username">
        <el-input v-model="forgetForm.username" placeholder="用户名" type="text"/>
      </el-form-item>
      <el-form-item prop="input">
        <el-input v-model="forgetForm.input" placeholder="邮箱" type="text"/>
      </el-form-item>
      <div class="drag">
        <div class="bg"/>
        <div class="text" onselectstart="return false;">请拖动滑块解锁</div>
        <div class="btn">>></div>
      </div>
      <div class="group">
        <el-button style="margin-right:20px;" @click.native.prevent="back">返 回</el-button>
        <el-button type="primary" @click.native.prevent="reset">重 置</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
  /* eslint-disable */
  import CryptoJS from 'crypto-js'
  import Layout from '@/layout'
  import { guid } from '@/utils'

  export default {
    name: 'Login',
    data() {
      return {
        loginForm: {
          username: '',
          password: ''
        },
        loginRules: {
          username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
          password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
        },
        forgetForm: {
          type: 'Email',
          username: '',
          input: ''
        },
        forgetRules: {
          username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
          input: [{ required: true, message: '邮箱不能为空', trigger: 'blur' }]
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined,
        menuData: [],
        isForget: false,
        forgetImgValid: false
      }
    },
    watch: {
      $route: {
        handler: function (route) {
          this.redirect = route.query && route.query.redirect
        },
        immediate: true
      }
    },
    methods: {
      forgetPwd() {
        this.isForget = true
        this.$nextTick(() => {
          this.init()
        })
      },
      back() {
        this.$refs['forgetForm'].resetFields()
        this.isForget = false
        this.forgetImgValid = false
      },
      reset() {
        this.$refs.forgetForm.validate(valid => {
          if (!valid) return
          if (!this.forgetImgValid) {
            this.$message.error('请先滑块验证')
            return
          }
          const data = Object.assign({}, this.forgetForm)
          this.$http.request({
            method: 'post',
            url: '/auth/retrievePassword',
            data: JSON.stringify(data)
          }).then(() => {
            this.$message.success('重置成功')
            this.back()
          })
        })
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        this.$refs.loginForm.validate((valid) => {
          if (!valid) return
          const uuid = window.localStorage.getItem('uuid')
          if (uuid) {
            this.uuid = uuid;
          } else {
            this.uuid = guid();
            window.localStorage.setItem('uuid', uuid)
            this.store.commit('uuid', uuid)
          }
          const { username, password } = this.loginForm
          this.$http.request({
            url: `/auth?tokenKey=get`
          }).then(res => {
            const { userKey, tokenKey: key } = res
            const tokenKey = CryptoJS.enc.Utf8.parse(key)
            const srcs = CryptoJS.enc.Utf8.parse(password)
            const pwd = CryptoJS.AES.encrypt(srcs, tokenKey, {
              iv: tokenKey,
              mode: CryptoJS.mode.CBC,
              padding: CryptoJS.pad.Pkcs7
            })
            this.$http.request({
              method: 'post',
              url: `/auth/login`,
              isLoadState: this,
              data: {
                username, password: String(pwd), userKey, timestamp: String(new Date().getTime()), deviceId: this.uuid
              }
            }).then(d => {
              if (d.jwt) {
                localStorage.setItem('account', JSON.stringify(d))
                this.$store.commit('account', d)
                this.getMenu(d)
              } else {
                this.$message.error('用户名，密码错误')
              }
            })
          })
        })
      },
      getMenu(account) {
        this.$http.request({
          url: `/resource/authorityMenu`,
          headers: {
            authorization: account.jwt,
            deviceId: this.uuid
          },
          data: {}
        }).then(res => {
          res.menuTree.forEach(menu => {
            const { code, name, uri, children, icon } = menu
            if (children.length) {
              let obj1 = {
                path: uri,
                component: Layout,
                meta: { title: name, icon },
                children: []
              }
              children.forEach(c => {
                this.buildMenuData(c, obj1.children, uri)
              })
              this.menuData.push(obj1)
            } else {
              let obj2 = {
                path: uri,
                component: Layout,
                children: [
                  {
                    path: 'index',
                    component: () => import(`@/views${uri}/index`),
                    meta: { title: name, icon }
                  }
                ]
              }
              this.menuData.push(obj2)
            }
          })
          this.$message.success('登录成功')
          this.$store.dispatch('app/setMenus', this.menuData)
          localStorage.setItem('menus', JSON.stringify(this.menuData))
          this.$router.addRoutes(this.menuData)
          console.log(this.menuData)
          this.$router.push({ path: '/layout' })
        })
      },
      buildMenuData(menu, data, pUri) {
        const { code, name, uri, children, icon } = menu
        if (children.length) {
          let obj1 = {
            path: pUri + uri,
            meta: { title: name, icon },
            component: () => import(`@/views${pUri}${uri}/index.vue`),
            children: []
          }
          children.forEach(c => {
            this.buildMenuData(c, obj1.children, pUri + uri)
          })
          data.push(obj1)
        } else {
          let obj2 = {
            path: pUri + uri,
            component: () => import(`@/views${pUri}${uri}/index.vue`),
            meta: { title: name, icon }
          }
          data.push(obj2)
        }
      },
      init() {
        const that = this
        // 一、定义一个获取DOM元素的方法
        var box = document.querySelector('.drag')
        var bg = document.querySelector('.bg') // 背景
        var text = document.querySelector('.text') // 文字
        var btn = document.querySelector('.btn') // 滑块
        var success = false // 是否通过验证的标志
        var distance = box.offsetWidth - btn.offsetWidth // 滑动成功的宽度（距离）
        btn.style.left = 0
        bg.style.width = 0
        btn.style.transition = 'left 1s ease'
        bg.style.transition = 'width 1s ease'
        btn.innerHTML = '>>'
        text.innerHTML = '请拖动滑块解锁'
        text.style.color = '#666'
        // 二、给滑块注册鼠标按下事件
        btn.onmousedown = function (e) {
          // 1.鼠标按下之前必须清除掉后面设置的过渡属性
          btn.style.transition = ''
          bg.style.transition = ''
          // 说明：clientX 事件属性会返回当事件被触发时，鼠标指针向对于浏览器页面(或客户区)的水平坐标。
          // 2.当滑块位于初始位置时，得到鼠标按下时的水平位置
          var e = e || window.event
          var downX = e.clientX
          // 三、给文档注册鼠标移动事件
          document.onmousemove = function (e) {
            var e = e || window.event
            // 1.获取鼠标移动后的水平位置
            var moveX = e.clientX
            // 2.得到鼠标水平位置的偏移量（鼠标移动时的位置 - 鼠标按下时的位置）
            var offsetX = moveX - downX
            // 3.在这里判断一下：鼠标水平移动的距离 与 滑动成功的距离 之间的关系
            if (offsetX > distance) {
              offsetX = distance // 如果滑过了终点，就将它停留在终点位置
            } else if (offsetX < 0) {
              offsetX = 0 // 如果滑到了起点的左侧，就将它重置为起点位置
            }
            // 4.根据鼠标移动的距离来动态设置滑块的偏移量和背景颜色的宽度
            btn.style.left = offsetX + 'px'
            bg.style.width = offsetX + 'px'
            // 如果鼠标的水平移动距离 = 滑动成功的宽度
            if (offsetX === distance) {
              // 1.设置滑动成功后的样式
              text.innerHTML = '验证通过'
              text.style.color = '#fff'
              btn.innerHTML = '√'
              btn.style.color = 'green'
              bg.style.backgroundColor = 'lightgreen'
              that.forgetImgValid = true
              // 2.设置滑动成功后的状态
              success = true
              // 成功后，清除掉鼠标按下事件和移动事件（因为移动时并不会涉及到鼠标松开事件）
              btn.onmousedown = null
              document.onmousemove = null
            }
          }
          // 四、给文档注册鼠标松开事件
          document.onmouseup = e => {
            // 如果鼠标松开时，滑到了终点，则验证通过
            if (success) {
              return
            } else {
              // 反之，则将滑块复位（设置了1s的属性过渡效果）
              btn.style.left = 0
              bg.style.width = 0
              btn.style.transition = 'left 1s ease'
              bg.style.transition = 'width 1s ease'
            }
            // 只要鼠标松开了，说明此时不需要拖动滑块了，那么就清除鼠标移动和松开事件。
            document.onmousemove = null
            document.onmouseup = null
          }
        }
      }
    }
  }
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg: #283443;
  $light_gray: #fff;
  $cursor: #fff;

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #eee;

  .forget {
    margin: 0 0 15px 0;
    float: right;
  }

  .group {
    text-align: center;
  }

  .drag {
    width: 98%;
    height: 40px;
    line-height: 40px;
    background-color: #fff;
    position: relative;
    margin: 15px auto;
  }

  .bg {
    width: 40px;
    height: 100%;
    position: absolute;
    background-color: #75CDF9;
  }

  .text {
    position: absolute;
    width: 100%;
    height: 100%;
    text-align: center;
    user-select: none;
  }

  .btn {
    width: 40px;
    height: 38px;
    position: absolute;
    border: 1px solid #ccc;
    cursor: move;
    font-family: "宋体";
    text-align: center;
    background-color: #fff;
    user-select: none;
    color: #666;
    line-height: 30px;
  }

  .login-container {
    min-height: 100%;
    width: 100%;
    background-color: $bg;
    overflow: hidden;

    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 160px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .el-button + .el-button {
      margin: 0;
    }
  }
</style>
